/**
 * @author Tobias Boehm
 *
 * 28.03.2011
 */
package org.anddev.andengine.extension.tbsengine.resource;

import org.anddev.andengine.extension.tbsengine.gameobject.Unit;
import org.anddev.andengine.extension.tbsengine.gameobject.ability.AbsAbility;

/**
 * This is an ability for {@link Unit}s to produce resources.
 * 
 * @author Tobias Boehm
 *
 */
public abstract class ResourceProducerAbility extends AbsAbility {

	protected ResourceAccount mResourceAccount;
	protected final AbsBaseResourceType mResourceType;
	protected final int mProductionAmount;
	
	public ResourceProducerAbility(final AbsBaseResourceType pResourceType, final int pProductionAmount, final String pName, final String pDescription, final int pIconTileID){
		super(pName, pDescription, pIconTileID);
		
		this.mProductionAmount = pProductionAmount;
		this.mResourceType = pResourceType;
	}
	
	public void setResourceAccount(final ResourceAccount pResourceAccount){
		
		if(!pResourceAccount.getResourceType().equals(this.mResourceType)){
			
			throw new IllegalArgumentException("ResourceAccount has to contain the same AbsBaseResourceType");
		}
		
		this.mResourceAccount = pResourceAccount;
	}
	
	public void removeResourceAccount(){
		
		this.mResourceAccount = null;
	}
	
	public void onTick(){
		
		if(checkProductionDone()){
		
			this.spreadResources();
		}
	}
	
	protected abstract boolean checkProductionDone();
	
	protected void spreadResources(){
		
		if(this.mResourceAccount != null){
			
			if(this.mResourceAccount.hasAmountMAX()){
				
				final int reducedAmount = Math.min((this.mResourceAccount.getAmountMAX() - this.mResourceAccount.getResourceAmount()),this.mProductionAmount);
				
				try {
					this.mResourceAccount.transact(reducedAmount);
				} catch (ResourceAccountLimitExceededException e) {}
				
			}else{
			
				try {
					this.mResourceAccount.transact(this.mProductionAmount);
				} catch (ResourceAccountLimitExceededException e) {}
			}	
		}
	}
}
